import TagGroup from '@/components/TagGroup';
import UploadDragger from '@/pages/cues/components/UploadDragger';
import {
  initSaveActiveTreeAssignOrganization,
  saveCuesActive,
} from '@/services/api/api-cues-active';
import { listCuesIndustry } from '@/services/api/api-cues-industry';
import {
  CheckCircleTwoTone,
  FileSearchOutlined,
  PlusOutlined,
  SendOutlined,
} from '@ant-design/icons';
import {
  DrawerForm,
  ModalForm,
  ProCard,
  ProFormCascader,
  ProFormDatePicker,
  ProFormInstance,
  ProFormList,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProList,
} from '@ant-design/pro-components';

import { ActionType } from '@ant-design/pro-table';
import { Button, Cascader, Col, Form, message, Modal, Row } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import { DefaultOptionType } from 'antd/es/select';
import { DataNode } from 'antd/es/tree';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddActivePreview from './AddActivePreview';
import { isEmpty } from 'lodash';

interface AddActiveProps {
  onRefurbish: () => void;
}

const AddActive: React.FC<AddActiveProps> = ({ onRefurbish }) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const formRef = useRef<ProFormInstance>();

  const [industrys, setIndustrysState] = useState<any[]>([]);

  const [openAddActive, setOpenAddActive] = useState<boolean>();

  const [openAddActivePreview, setOpenAddActivePreview] = useState<boolean>(false);
  const [previewData, setPreviewData] = useState<CuesActiveBo.AddActivePreview>();

  const [green, setGreen] = useState<boolean>(false);

  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  const [open, setOpen] = useState(false);
  /**
   * 推送单位数据
   */
  const [treeAssignOrganizationData, setTreeAssignOrganizationDataState] = useState<DataNode[]>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载 保存 推送 单位
   */
  const loadInitSaveActiveTreeAssignOrganization = async () => {
    try {
      const response = await initSaveActiveTreeAssignOrganization();
      if (response.code === 0) {
        setTreeAssignOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  /**
   * 加载权限详情
   * @param key
   */
  const getCuesIndustryData = async () => {
    try {
      const response = await listCuesIndustry();

      setIndustrysState(
        response.data.map((item) => {
          return { label: item.name, value: item.id };
        }),
      );
    } catch (error) {}
  };

  /**
   * 级联组件 搜索筛选
   * @param inputValue
   * @param path
   * @returns
   */
  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  const handleOk = () => {
    setTimeout(() => {
      setOpen(false);
    }, 2000);
  };

  const handleCancel = () => {
    console.log('Clicked cancel button');
    setOpen(false);
  };
  return (
    <>
      <DrawerForm
        key="drawer_form_add_submit"
        title="报送线索"
        drawerProps={{
          maskClosable: false,
          destroyOnClose: true,
          width: 680,
        }}
        formRef={formRef}
        trigger={
          <Button key="button_add_submit" type="primary">
            <PlusOutlined />
            报送线索
          </Button>
        }
        initialValues={{}}
        open={openAddActive}
        onOpenChange={(visible) => {
          setOpenAddActive(visible);
          if (visible) {
            getCuesIndustryData();
            loadInitSaveActiveTreeAssignOrganization();
          } else {
            setTreeAssignOrganizationDataState([]);
          }
        }}
        layout="horizontal"
        submitter={{
          searchConfig: {
            submitText: (
              <>
                <FileSearchOutlined /> 预览
              </>
            ),
          },
          render: (props, defaultDoms) => {
            return [
              defaultDoms,
              <AddActivePreview
                key="add_active_preview"
                onSubmit={() => {
                  setOpenAddActive(false);
                  setOpen(true);
                  onRefurbish();
                }}
                open={openAddActivePreview}
                onOpenChange={(open) => {
                  setOpenAddActivePreview(open);
                }}
                details={previewData}
              />,
              <Button
                key="button_add_submit"
                icon={<SendOutlined />}
                type="primary"
                style={{
                  background: '#87d068',
                }}
                onClick={() => {
                  /**
                   * ======================
                   * 直接发布
                   * ======================
                   */
                  const values = formRef.current?.getFieldsValue();

                  if (!(values.articleName !== undefined && values.articleName.length > 0)) {
                    message.warning('请输入标题');
                    return;
                  }

                  if (
                    !(
                      values.articleIndustryIds !== undefined &&
                      values.articleIndustryIds.length > 0
                    )
                  ) {
                    message.warning('请选择至少一个选题方向');
                    return;
                  }

                  if (!(values.articleLabels !== undefined && values.articleLabels.length > 0)) {
                    message.warning('请输入至少一个标签');
                    return;
                  }

                  if (!(values.articleContent !== undefined && values.articleContent.length > 0)) {
                    message.warning('请输入线索内容');
                    return;
                  }
                  if (!(values.contacts && values.contacts.length > 0)) {
                    console.log('====');
                  } else {
                    let required = false;
                    let unable = false;
                    const phoneRegex =
                      /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
                    values.contacts.forEach((element: { name: any; phone: any }) => {
                      if (element.phone == undefined || element.phone.length == 0 || isEmpty(element.name)) {
                        required = true;
                      }
                      if (!phoneRegex.test(element.phone)) {
                        unable = true;
                      }
                    });

                    if (required) {
                      message.warning('请补充联络人信息');
                      return;
                    }
                    if (unable) {
                      message.warning('请输入正确的联系电话');
                      return;
                    }
                  }

                  setModalFormOpenState(true);
                }}
              >
                提交
              </Button>,
              <ModalForm
                key={'modal_form_add_submit'}
                title={
                  <>
                    <CheckCircleTwoTone
                      style={{
                        marginRight: 8,
                      }}
                      twoToneColor="#87d068"
                    />
                    确认提交
                  </>
                }
                autoFocusFirstInput
                modalProps={{
                  width: 400,
                  destroyOnClose: true,
                }}
                open={modalFormOpen}
                onOpenChange={setModalFormOpenState}
                submitTimeout={2000}
                submitter={{
                  submitButtonProps: {
                    type: 'primary',
                    style: { background: '#87d068' },
                  },
                }}
                onFinish={async () => {
                  const values = formRef.current?.getFieldsValue();

                  if (
                    values.articleAttachments !== undefined &&
                    values.articleAttachments.length > 0
                  ) {
                    const articleAttachments = values.articleAttachments.map(
                      (item: { response: { data: { id: any } } }) => {
                        return item.response.data.id;
                      },
                    );
                    values.articleAttachments = articleAttachments;
                  }

                  if (values.articleSetDate) {
                    values.articleSetDate = dayjs(values.articleSetDate).format('YYYY-MM-DD');
                  }

                  const response = await saveCuesActive({
                    articleName: values?.articleName,
                    articleIndustryIds: values?.articleIndustryIds,
                    articleLabels: values?.articleLabels,
                    assignOrganizationIds: values?.assignOrganizationIds,
                    articleSetDate: values.articleSetDate,
                    articleLocation: values.articleLocation,
                    articleHighlight: values.articleHighlight,
                    contacts: values.contacts,
                    articleContent: values?.articleContent,
                    articleAttachments: values.articleAttachments,
                    createdSource: 1,
                  });

                  if (response.code === 0) {
                    message.success('提交成功');
                    setOpenAddActive(false);
                    setOpen(true);
                    onRefurbish();
                    return true;
                  } else {
                    return false;
                  }
                }}
              />,
            ];
          },
        }}
        onFinish={async (values) => {
          if (
            values.articleName === undefined ||
            values.articleName.length === 0 ||
            values.articleName.trim() === ''
          ) {
            message.warning('请输入标题');
            return;
          }

          if (values.articleIndustryIds === undefined || values.articleIndustryIds.length === 0) {
            message.warning('请选择最少一个选题方向');
            return;
          }

          if (values.articleLabels === undefined || values.articleLabels.length === 0) {
            message.warning('请输入最少一个标签');
            return;
          }

          if (!(values.contacts && values.contacts.length > 0)) {

          } else {
            let required = false;
            let unable = false;
            const phoneRegex =
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
            values.contacts.forEach((element: { name: any; phone: any }) => {
              console.log('====', element, phoneRegex.test(element.phone));
              if (element.phone == undefined || element.phone.length == 0 || isEmpty(element.name) ) {
                required = true;
              }
              if (!phoneRegex.test(element.phone)) {
                unable = true;
              }
            });

            if (required) {
              message.warning('请补充联络人信息');
              return;
            }
            if (unable) {
              message.warning('请输入正确的联系电话');
              return;
            }
          }

          if (
            values.articleContent === undefined ||
            values.articleContent.length === 0 ||
            values.articleContent.trim() === ''
          ) {
            message.warning('请输入线索内容');
            return;
          }

          const articleIndustrys = values.articleIndustryIds?.map((item: any) => {
            const industry = industrys.find((e) => e.value === item);
            return industry;
          });

          if (values.articleSetDate) {
            values.articleSetDate = dayjs(values.articleSetDate).format('YYYY-MM-DD');
          }

          setPreviewData({
            articleName: values.articleName,
            articleIndustrys: articleIndustrys,
            articleLabels: values.articleLabels,
            articleSetDate: values.articleSetDate,
            articleLocation: values.articleLocation,
            articleHighlight: values.articleHighlight,
            contacts: values.contacts,
            assignOrganizationIds: values.assignOrganizationIds,
            articleContent: values.articleContent,
            articleAttachments: values.articleAttachments,
            createdSource: 1,
            showTreeAssignOrganizationData: treeAssignOrganizationData,
          });
          setOpenAddActivePreview(true);
        }}
      >
        <ProFormText
          width="xl"
          name="articleName"
          label={
            <span>
              <span
                style={{
                  color: '#ff4d4f',
                  fontSize: 14,
                  paddingRight: 4,
                }}
              >
                *
              </span>
              标题
            </span>
          }
          fieldProps={{
            allowClear: true,
            maxLength: 50,
            showCount: true,
            style: {
              marginLeft: '28px',
            },
          }}
        />
        <ProFormSelect
          width="xl"
          name="articleIndustryIds"
          label={
            <>
              <span
                style={{
                  color: '#ff4d4f',
                  fontSize: 14,
                  paddingRight: 4,
                }}
              >
                *
              </span>
              选题方向
            </>
          }
          options={industrys}
          fieldProps={{
            mode: 'multiple',
            allowClear: true,
            style: {
              marginLeft: '0',
            },
          }}
          extra={'最少选择一个'}
        />
        <Form.Item
          label={
            <>
              <span
                style={{
                  color: '#ff4d4f',
                  fontSize: 14,
                  paddingRight: 4,
                }}
              >
                *
              </span>
              标签
            </>
          }
          name="articleLabels"
          extra={
            <div
              style={{
                marginLeft: '28px',
              }}
            >
              最少输入一个
            </div>
          }
        >
          <TagGroup
            style={{
              marginLeft: '28px',
            }}
          />
        </Form.Item>

        <ProFormDatePicker
          name="articleSetDate"
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              线索日期
            </span>
          }
          width="xl"
          fieldProps={{
            allowClear: true,
            maxLength: 200,
            format: 'YYYY-MM-DD',
          }}
        />
        <ProFormTextArea
          name="articleLocation"
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              地点
            </span>
          }
          width="xl"
          fieldProps={{
            allowClear: true,
            rows: 3,
            maxLength: 100,
            showCount: true,
            style: {
              marginLeft: '28px',
            },
          }}
        />

        <ProFormTextArea
          name="articleHighlight"
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              亮点
            </span>
          }
          width="xl"
          fieldProps={{
            allowClear: true,
            rows: 3,
            maxLength: 100,
            showCount: true,
            style: {
              marginLeft: '28px',
            },
          }}
        />

        <ProFormList
          name="contacts"
          label="联络方式"
          creatorButtonProps={{
            creatorButtonText: '添加联络人',
          }}
          itemRender={({ listDom, action }, { index }) => {
            return (
              <ProCard
                bordered
                title={false}
                style={{
                  marginBlockEnd: 8,
                }}
                bodyStyle={{
                  paddingBottom: 0,
                }}
              >
                <Row>
                  <Col span={23}>{listDom}</Col>
                  <Col span={1}>{action}</Col>
                </Row>
              </ProCard>
            );
          }}
          copyIconProps={false}
        >
          <ProFormText
            width="md"
            name="name"
            label="联络人"
            required={true}
            fieldProps={{
              allowClear: true,
              maxLength: 200,
            }}
          />
          <ProFormText
            width="md"
            name="phone"
            label="联系电话"
            required={true}
            fieldProps={{
              allowClear: true,
              maxLength: 200,
            }}
            rules={[
              {
                pattern:
                  /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                message: '请输入正确的手机号',
              },
            ]}
          />
        </ProFormList>
        <ProFormCascader
          width="xl"
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              报送媒体
            </span>
          }
          name="assignOrganizationIds"
          placeholder="选择媒体"
          extra={'不选择，默认推送给所有媒体单位'}
          fieldProps={{
            options: treeAssignOrganizationData,
            showSearch: { filter },
            multiple: true,
            removeIcon: true,
            allowClear: true,
            maxTagCount: 'responsive',
            showCheckedStrategy: Cascader.SHOW_CHILD,
          }}
        />
        <ProCard ghost>
          <ProCard colSpan={green ? '750px' : '1'} ghost>
            <ProFormTextArea
              name="articleContent"
              label={
                <span>
                  <span
                    style={{
                      color: '#ff4d4f',
                      fontSize: 14,
                      paddingRight: 4,
                    }}
                  >
                    *
                  </span>
                  线索内容
                </span>
              }
              width="xl"
              fieldProps={{
                allowClear: true,
                rows: 5,
                maxLength: 200,
                showCount: true,
              }}
            />
          </ProCard>
          {green && (
            <ProCard ghost>
              <ProList
                extra={<a>aa</a>}
                rowKey="id"
                headerTitle={false}
                toolbar={{}}
                dataSource={[
                  {
                    id: '1',
                    name: '语雀的天空',
                    image:
                      'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
                    desc: '我是一条测试的描述',
                  },
                  {
                    id: '2',
                    name: 'Ant Design',
                    image:
                      'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
                    desc: '我是一条测试的描述',
                  },
                  {
                    id: '3',
                    name: '蚂蚁金服体验科技',
                    image:
                      'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
                    desc: '我是一条测试的描述',
                  },
                  {
                    id: '4',
                    name: 'TechUI',
                    image:
                      'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
                    desc: '我是一条测试的描述',
                  },
                ]}
                showActions="hover"
                editable={{
                  onSave: async (key, record, originRow) => {
                    console.log(key, record, originRow);
                    return true;
                  },
                }}
                metas={{
                  title: {
                    dataIndex: 'name',
                  },
                  description: {
                    dataIndex: 'desc',
                  },

                  actions: {
                    render: (text, row, index, action) => [
                      <a
                        onClick={() => {
                          action?.startEditable(row.id);
                        }}
                        key="link"
                      >
                        编辑
                      </a>,
                    ],
                  },
                }}
              />
            </ProCard>
          )}
        </ProCard>
        <FormItem
          name="articleAttachments"
          hidden={!access.主动报送x报送线索x附件}
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              附件
            </span>
          }
        >
          <UploadDragger
            style={{
              marginLeft: '28px',
            }}
            onPreview={(file) => {}}
            access={{
              isPicture: access.主动报送x报送线索x附件x图片,
              isVideo: access.主动报送x报送线索x附件x视频,
              isOffice: access.主动报送x报送线索x附件x办公,
              isOther: access.主动报送x报送线索x附件x其他,
            }}
            url="/cues/attachment/save"
            mode="active"
          />
        </FormItem>
      </DrawerForm>
      <Modal
        title="是否继续报送"
        open={open}
        onOk={() => {
          setOpenAddActive(true), setOpen(false);
        }}
        // confirmLoading={confirmLoading}
        onCancel={() => setOpen(false)}
      >
        <p>是否再报送一篇线索</p>
      </Modal>
    </>
  );
};
export default AddActive;
